package com.heima.user.filter;

import com.heima.user.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@RefreshScope
@Slf4j
@Component
@Order(-1)
public class UserLoginFilter implements GlobalFilter {

    @Value("${ignoreUrl}")
    private List<String> ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //放行登录的请求
        String path = request.getURI().getPath();
        if (ignoreUrl.contains(path)){
            return chain.filter(exchange);
        }

        //查看token是否为空是否过期
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            log.info("token为空,不能执行了");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //token不为空的话，解析
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i==1||i==2){
            log.info("token过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //都可以的话就放行
        return chain.filter(exchange);
    }
}
